import { io } from 'socket.io-client';
import { useBoardStore } from '../stores/board';
import { useCardStore } from '../stores/card';

const socket = io('/boards', {
  auth: {
    token: localStorage.getItem('token')
  }
});

export const initRealtime = () => {
  const boardStore = useBoardStore();
  const cardStore = useCardStore();

  socket.on('connect', () => {
    console.log('Connected to realtime server');
  });

  socket.on('board:update', (data) => {
    boardStore.updateBoardInStore(data);
  });

  socket.on('card:move', (data) => {
    cardStore.updateCardPosition(data);
  });

  socket.on('card:update', (data) => {
    cardStore.updateCardInStore(data);
  });

  socket.on('list:create', (data) => {
    boardStore.addListToBoard(data);
  });

  socket.on('list:update', (data) => {
    boardStore.updateListInBoard(data);
  });

  socket.on('disconnect', () => {
    console.log('Disconnected from realtime server');
  });

  return {
    subscribeToBoard: (boardId) => {
      socket.emit('subscribe', boardId);
    },
    unsubscribeFromBoard: (boardId) => {
      socket.emit('unsubscribe', boardId);
    }
  };
}; 